using System;
using System.Diagnostics;
using System.IO;
using SolutionFactory.Services;

namespace SolutionFactory
{
    public class ProcessExecutor : IProcessExecutor
    {
        private readonly ILogger _logger;

        public ProcessExecutor(ILogger logger)
        {
            _logger = logger;
        }

        #region IProcessExecutor Members

        public void Execute(string path)
        {
            Execute("cmd.exe", Path.GetDirectoryName(path) , @"/C """"" + Path.GetFileName(path) + @"""""", true);
        }

        public void Execute(string path, string workingDirectory, string arguments, bool useShellExecute)
        {
            var process = new Process();
            process.StartInfo.UseShellExecute = useShellExecute;
            if (!useShellExecute)
            {
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardOutput = true;
            }
            process.StartInfo.FileName = path;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.WorkingDirectory = workingDirectory;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            process.Start();
            process.WaitForExit();
            if(!useShellExecute)
            {
                _logger.Log(process.StandardOutput.ReadToEnd());            
            }
            if(process.ExitCode!=0)
            {
                _logger.Log(process.StandardError.ReadToEnd());
                throw new Exception("Failed to exectue process. ");//+ process.StandardError.ReadToEnd());
            }            
        }
        #endregion
    }
}